package com.voxel.sense.infomsg.module.publish;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.ToastUtil;
import com.lzy.okgo.model.Progress;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.FileImageInfo;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.interfaces.listener.UploadListenerImp;
import com.voxel.sense.infomsg.utils.UploadManager;
import com.voxel.sense.infomsg.utils.manager.QueryConfigManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.FirmNameByIdEntity;
import cyy.example.com.facotry.model.api.response.SearchMenuEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.NetHelper;

/**
 * Created by ChenYiYao on 2018/8/31.
 */
public class PublishFilePresenter extends BasePresenter<PublishContract.View> implements PublishContract.Presenter,
        DataSource.Callback<BaseEntity<List<FirmNameByIdEntity>>> {

    private boolean mISLoadFirmList;
//    private ArrayList<String> mSelectImagePath;//选择图片返回的path
    private UploadManager mUploadManager;

    public PublishFilePresenter(PublishContract.View view) {
        super(view);
    }

    @Override
    public void start() {
        super.start();
//        mSelectImagePath = new ArrayList<>();
        EventBus.getDefault().register(this);
    }

    @Override
    public void destroy() {
        super.destroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void doLoadTypeData() {
        SearchMenuEntity publishFileType = QueryConfigManager.getInstance().getPublishFileType();
        if (publishFileType != null && publishFileType.getStaticSystemConstantDetails() != null) {
            List<ConditionBean> list = new ArrayList<>();
            List<SearchMenuEntity.StaticSystemConstantDetailsBean> staticSystemConstantDetails = publishFileType.getStaticSystemConstantDetails();
            for (SearchMenuEntity.StaticSystemConstantDetailsBean bean : staticSystemConstantDetails) {
                ConditionBean conditionBean = new ConditionBean(Constants.PUBLISH_FILE_TYPE, bean.getConstantCode(), bean.getConstantName(), false);
                list.add(conditionBean);
            }
            if (list == null || list.size() < 1) {
//                mView.showError("获取发布类型失败");
                ToastUtil.showToastLong(Factory.app(), "获取上传类型失败");
            } else {
                mView.onUpTypeUi(list);

            }
        } else if (!NetworkUtils.isConnected()) {
            //没有数据，同时网络不可用
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.network_unavailable));
        }

    }

    @Override
    public void doLoadFirmList() {
        if (!mISLoadFirmList) {
            NetHelper.getSearchFirmById("", this);
        }

    }

    @Override
    public void doHanlderTakePhotoResult(File file) {
        if (FileUtils.isFileExists(file)) {
            Intent borad = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            borad.setData(Uri.fromFile(file));
            Factory.app().sendBroadcast(borad);
        } else {
            mView.showError("获取拍摄照片失败");
        }
    }




    @Override
    public void doHandlerSelectPicResult(List<String> strings) {
        ArrayList<FileImageInfo> listImageData = new ArrayList<>();
        for (int i = 0; i < strings.size(); i++) {
            File file = new File(strings.get(i));
            if (file.exists()) {
                FileImageInfo fileImageInfo = new FileImageInfo(file.getName(), file.getPath());
                listImageData.add(fileImageInfo);
            }
        }

        mView.onRefreshSelectPhoto(listImageData);
    }

    @Override
    public void doSubmitContent(String textContent, String firmName, String id, String type,List<String> files) {
        if (TextUtils.isEmpty(id)) {
            mView.showError("请填写正确的公司");
        } else if (TextUtils.isEmpty(type)) {
            mView.showError("请选择类型");
        } else if (TextUtils.isEmpty(textContent) && (files == null || files.size() < 1)) {
            //TODO: 暂时隐藏上传文件
//            mView.showError("请添加意见或者上传照片");
            mView.showError("请添加意见");
        } else if (!NetworkUtils.isConnected()) {
            ToastUtil.showToastLong(Factory.app(), R.string.network_unavailable);
        } else {

            if (mUploadManager == null) {
                mUploadManager = new UploadManager();
                mUploadManager.setShowProgress(true);

                mUploadManager.initProgressDialog((Context) mView, "发布中");
            }
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("fileStr", textContent);
            stringMap.put("companyId", id);
            stringMap.put("fileType", type);
            long l = System.currentTimeMillis();
            mUploadManager.getPostUpRequest(l + "", stringMap, files, id, new UploadListenerImp<String>() {
                @Override
                public void onError(Progress progress) {
                    ToastUtil.showToastLong(Factory.app(), "上传失败");
                }

                @Override
                public void onRemove(Progress progress) {
                    ToastUtil.showToastLong(Factory.app(), "上传失败");
                }

                @Override
                public void onFinish(String str, Progress progress) {
                    if (mView != null) {
                        try {
                            BaseEntity baseEntity = Factory.getGson().fromJson(str, BaseEntity.class);
                            if (baseEntity.isSuccess()) {
                                mView.onSubmitSuccess();
                            } else {
                                ToastUtil.showToastLong(Factory.app(), "上传失败");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }


    @Override
    public void onDataLoaded(BaseEntity<List<FirmNameByIdEntity>> data, int reqId) {
        if (mView == null) {
            return;
        }

        if (reqId == RequestIdFactory.SEARCH__FIRM_NAME_ID) {
            mISLoadFirmList = false;
            if (data.isSuccess()) {
                List<FirmNameByIdEntity> firmDatas = data.getData();
                if (firmDatas.size() > 0) {
                    mView.onShowFirmList(firmDatas);
                }
            }
        }
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (reqId == RequestIdFactory.SEARCH__FIRM_NAME_ID) {
            mISLoadFirmList = false;
        }
    }

    @Subscribe
    public void onEventThread(EventEntity event) {
        if (event.key.equals(String.valueOf(EventBusConstants.QUERY_CONFIG))) {
            //收到搜索配置文件加载完成的消息
            if (event.value.equals(EventBusConstants.SUCCEED) && mView != null) {
                //刷新列表
                doLoadTypeData();

            }
        }
    }

}
